;; Copyright (c) 2022 bobwxc@yeah.net
;; This program is free software: you can redistribute it and/or modify it under
;; the terms of the GNU Lesser General Public License as published by the Free Software
;; Foundation, either version 3 of the License, or (at your option) any later
;; version.
;; This program is distributed in the hope that it will be useful, but WITHOUT
;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
;; FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
;; details.
;; You should have received a copy of the GNU General Public License along with
;; this program. If not, see <https://www.gnu.org/licenses/>.

(in-package #:simple-tar)

(defclass tar-file ()
  ((path :initarg :path
         :reader tar-file-path
         :documentation "file path")
   (mode :initarg :mode
         :reader tar-file-mode
         :initform :input
         :documentation "file direction, :input :output or :io")
   (fs :accessor tar-file-stream
       :documentation "file stream of path")
   )
  )

(defmethod initialize-instance :after ((obj tar-file) &rest initargs &key &allow-other-keys)
  (cond
   ((equal (tar-file-mode obj) :input)
    (setf (tar-file-stream obj) (open (tar-file-path obj)
                                      :direction :input
                                      :element-type '(unsigned-byte 8)
                                      :if-does-not-exist :error)))
   ((equal (tar-file-mode obj) :output)
    (setf (tar-file-stream obj) (open (tar-file-path obj)
                                      :direction :output
                                      :element-type '(unsigned-byte 8)
                                      :if-exists :rename)))
   ((equal (tar-file-mode obj) :io)
    (setf (tar-file-stream obj) (open (tar-file-path obj)
                                      :direction :io
                                      :element-type '(unsigned-byte 8)
                                      :if-does-not-exist :error))))
  )

;; (print (make-instance 'tar-file :path "./test.txt" :mode :output))

(defmethod next-file ((obj tar-file))
  (read-next-file (tar-file-stream obj)))

(defmethod all-files ((obj tar-file))
  (read-all-files (tar-file-stream obj)))

(defmethod append-file ((obj tar-file) head body)
  (write-one-file (tar-file-stream obj) head body))

(defmethod close-file ((obj tar-file))
  (close (tar-file-stream obj)))

